package com.wei.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wei.dto.KeyValueDTO;
import com.wei.mapper.*;
import com.wei.model.*;
import com.wei.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wei.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author 蔡徐坤
 * @since 2025-07-28
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> implements IProductService {

    private final ReviewMapper reviewMapper;

    private final ProductCategoryRelMapper productCategoryRelMapper;

    private final CategoryMapper categoryMapper;

    private final ProductTagRelMapper productTagRelMapper;

    private final TagMapper tagMapper;

    private final ProductMapper productMapper;

    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public ProductDO getProductById(Long id) {
        ProductDO product = this.getById(id);
        // 查评分
        product.setRating(this.getRating(id));
        // 查分类
        product.setCategories(this.getCategoryNameList(id));
        // 查标签
        product.setTags(this.getTagNameList(id));
        // 转换更多信息
        try {
            product.setAdditionalInfoList(JsonUtil.json2List(product.getAdditionalInfo(), KeyValueDTO.class));
        } catch (Exception e) {
            if (StringUtils.hasText(product.getAdditionalInfo())) {
                product.setAdditionalInfoList(Collections.singletonList(new KeyValueDTO("info", product.getAdditionalInfo())));
            }
        }
        return product;
    }

    @Override
    @Cacheable(value = { "jewelry:product" }, key = "#root.methodName", sync = true)
    public List<ProductDO> findAll() {
        return productMapper.selectAll();

    }

    private String getAllProductStr() {
        String key = "jewelry:product:list";
        // 先查缓存
        String productListCache = stringRedisTemplate.opsForValue().get(key);
        if (productListCache != null && !productListCache.isEmpty()) {
            // 有缓存直接返回缓存
            System.err.println("有缓存");
            return productListCache;
        } else {
            System.err.println("没缓存");
            // 没缓存 -> 上锁，查询数据库
            synchronized (this) {
                // 拿到锁后再查一次缓存
                productListCache = stringRedisTemplate.opsForValue().get(key);
                if (productListCache != null && !productListCache.isEmpty()) {
                    // 有缓存直接返回缓存
                    return productListCache;
                }
                // 查询数据库
                List<ProductDO> productList = productMapper.selectAll();
                // 设置缓存
                String res = JSON.toJSONString(productList);
                stringRedisTemplate.opsForValue().set(key, res);
                return res;
            }
        }
    }

    /**
     * 获取评分
     */
    private Double getRating(Long id) {
        List<ReviewDO> reviews = reviewMapper.selectList(new LambdaQueryWrapper<ReviewDO>().eq(ReviewDO::getProductId, id));
        if (reviews == null || reviews.isEmpty()) {
            return 5d;
        }
        Double sum = 0d;
        for (ReviewDO review : reviews) {
            sum += review.getRating();
        }
        return sum / reviews.size();
    }

    /**
     * 获取分类
     */
    private List<String> getCategoryNameList(Long id) {
        List<ProductCategoryRelDO> rels = productCategoryRelMapper.selectList(new LambdaQueryWrapper<ProductCategoryRelDO>()
                .eq(ProductCategoryRelDO::getProductId, id));
        if (rels == null || rels.isEmpty()) {
            return null;
        }
        List<Long> categoryIdList = rels.stream().map(ProductCategoryRelDO::getCategoryId).collect(Collectors.toList());
        List<CategoryDO> categories = categoryMapper.selectList(new LambdaQueryWrapper<CategoryDO>().in(CategoryDO::getId, categoryIdList));
        return categories.stream().map(CategoryDO::getName).collect(Collectors.toList());
    }

    /**
     * 获取标签
     */
    private List<String> getTagNameList(Long id) {
        List<ProductTagRelDO> rels = productTagRelMapper.selectList(new LambdaQueryWrapper<ProductTagRelDO>()
                .eq(ProductTagRelDO::getProductId, id));
        if (rels == null || rels.isEmpty()) {
            return null;
        }
        List<Long> tagIdList = rels.stream().map(ProductTagRelDO::getTagId).collect(Collectors.toList());
        List<TagDO> categories = tagMapper.selectList(new LambdaQueryWrapper<TagDO>().in(TagDO::getId, tagIdList));
        return categories.stream().map(TagDO::getName).collect(Collectors.toList());
    }

}
